layui.define(['config', 'layer', 'element', 'form'], function (exports) {
    var config = layui.config;
    var layer = layui.layer;
    var element = layui.element;
    var form = layui.form;
    var $ = layui.jquery;
    var popupRightIndex, popupCenterIndex, popupCenterParam;

    var crown = {
        // 设置侧栏折叠
        flexible: function (expand) {
            var isExapnd = $('.layui-layout-admin').hasClass('crown-nav-mini');
            if (isExapnd == !expand) {
                return;
            }
            if (expand) {
                $('.layui-layout-admin').removeClass('crown-nav-mini');
            } else {
                $('.layui-layout-admin').addClass('crown-nav-mini');
            }
            crown.onResize();
        },
        // 右侧弹出
        popupRight: function (path) {
            popupRightIndex = layer.open({
                type: 1,
                id: 'crownPopupR',
                anim: 2,
                isOutAnim: false,
                title: false,
                closeBtn: false,
                offset: 'r',
                shade: .2,
                shadeClose: true,
                resize: false,
                area: '336px',
                skin: 'layui-layer-crownRight',
                success: function () {
                    //crown.showLoading('#crownPopupR');
                    $('#crownPopupR').load(path, function () {
                        //crown.removeLoading('#crownPopupR');
                    });
                },
                end: function () {
                    layer.closeAll('tips');
                }
            });
        },
        // 关闭右侧弹出
        closePopupRight: function () {
            layer.close(popupRightIndex);
        },
        // 中间弹出
        popupCenter: function (param) {
            popupCenterParam = param;
            popupCenterIndex = layer.open({
                type: 1,
                id: 'crownPopupC',
                title: param.title ? param.title : false,
                shade: .2,
                offset: '45px',
                area: param.area ? param.area : '450px',
                resize: false,
                skin: 'layui-layer-crownCenter',
                success: function () {
                    $('#crownPopupC').load(param.path, function () {
                        $('#crownPopupC .close').click(function () {
                            layer.close(popupCenterIndex);
                        });
                        param.success ? param.success() : '';
                    });
                },
                end: function () {
                    layer.closeAll('tips');
                    param.end ? param.end() : '';
                }
            });
        },
        // 关闭中间弹出并且触发finish回调
        finishPopupCenter: function () {
            layer.close(popupCenterIndex);
            popupCenterParam.finish ? popupCenterParam.finish() : '';
        },
        fromVal: function (filter, object) {
            var formElem = $('.layui-form[lay-filter="' + filter + '"]');
            formElem.each(function () {
                var itemFrom = $(this);
                layui.each(object, function (key, value) {
                    /* if (typeof (value) === 'object') {
                         fromVal(filter, value);//递归
                     }*/
                    var itemElem = itemFrom.find('[name="' + key + '"]');
                    //如果对应的表单不存在，则不执行
                    if (!itemElem[0]) {
                        return;
                    }
                    var type = itemElem[0].type;
                    //如果为复选框
                    if (type === 'checkbox') {
                        if (typeof (value) !== 'object') {
                            itemElem[0].checked = value;
                        } else {
                            layui.each(value, function (index, item) {
                                itemElem.each(function () {
                                    if (this.value === item.toString()) {
                                        this.checked = true;
                                    }
                                });
                            });
                        }
                    } else if (type === 'radio') { //如果为单选框
                        itemElem.each(function () {
                            if (this.value === value.toString()) {
                                this.checked = true;
                            }
                        });
                    } else { //其它类型的表单
                        itemElem.val(value);
                    }
                });
            });
            form.render(null, filter);
        },
        // 关闭中间弹出
        closePopupCenter: function () {
            layer.close(popupCenterIndex);
        },
        get: function (url, data, success, async) {
            return this.request(url, data, "GET", success, async);
        },
        post: function (url, data, success, async) {
            return this.request(url, data, "POST", success, async);
        },
        put: function (url, data, success, async) {
            return this.request(url, data, "PUT", success, async);
        },
        delete: function (url, data, success, async) {
            return this.request(url, data, "DELETE", success, async);
        },
        request: function (url, data, method, success, async) {
            var contentType;
            switch (method) {
                case "GET":
                    contentType = '';
                    break;
                case "POST":
                    data = JSON.stringify(data);
                    contentType = 'application/json; charset=UTF-8';
                    break;
                case "PUT":
                    data = JSON.stringify(data);
                    contentType = 'application/json; charset=UTF-8';
                    break;
                case "DELETE":
                    contentType = '';
                    break;
                default:
                    contentType = '';
            }
            $.ajax({
                url: url,
                data: data,
                type: method,
                contentType: contentType,
                xhrFields: {
                    withCredentials: false
                },
                async: async !== false,
                crossDomain: true,
                success: function (data) {
                    success(data);
                },
                error: function (xhr) {
                    if (xhr.responseJSON.error === 'UNAUTHORIZED') {
                        config.removeAll();
                        layer.msg('登录过期', {icon: 2}, function () {
                            location.href = '/login.html';
                        });
                        return false;
                    }
                    layer.msg(JSON.parse(xhr.responseText).msg, {icon: 5});
                    layer.closeAll('loading');
                },
                beforeSend: function (xhr) {
                    var token = config.getToken();
                    if (token) {
                        xhr.setRequestHeader('Authorization', token);
                    }
                }
            });
        },
        // 窗口大小改变监听
        onResize: function () {
            if (config.autoRender) {
                if ($('.layui-table-view').length > 0) {
                    setTimeout(function () {
                        crown.events.refresh();
                    }, 800);
                }
            }
        },
        // 显示加载动画
        showLoading: function (element) {
            $(element).append('<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop crown-loading"></i>');
        },
        // 移除加载动画
        removeLoading: function (element) {
            $(element + '>.crown-loading').remove();
        },
        // 缓存临时数据
        putTempData: function (key, value) {
            if (value) {
                layui.sessionData('tempData', {key: key, value: value});
            }
        },
        // 获取缓存临时数据 获取完删除
        getTempData: function (key) {
            var tempData = layui.sessionData('tempData')[key];
            layui.sessionData('tempData', {key: key, remove: true});
            return tempData;
        }
    };

    exports('crown', crown);
});
